package com.example.spring.controller;


import com.example.spring.constant.Constants;
import com.example.spring.util.HttpClientUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.TreeMap;

@RestController
public class WxMsgTempController {
    private Logger logger = LoggerFactory.getLogger(WxController.class);
    //微信模板接口
    private final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
    //模板消息详情跳转URL
    private static String url = "https://www.baidu.com/";

    /**
     * 1.用户同意授权，获取code
     */
    @RequestMapping(value = "/get_code_num", method = RequestMethod.GET)
    public String getCode() throws UnsupportedEncodingException {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Constants.APPID + "&redirect_uri="
                + URLEncoder.encode("http://192.168.0.152:8080/send_wx_msg", "UTF-8") + "&response_type=code&scope="
                + Constants.GRANTSCOPE + "&state=STATE#wechat_redirect";
    }

    /**
     * 2.通过code换取网页授权access_token及openid
     */
    @RequestMapping(value = "/send_wx_msg", method = RequestMethod.GET)
    public String sendWxMsg(String code) {
        String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        TreeMap<String, String> param1 = new TreeMap<String, String>();
        param1.put("appid", Constants.APPID);
        param1.put("secret", Constants.APPSECRET);
        param1.put("code", code);
        param1.put("grant_type", "authorization_code");
        String accessTokenObj = HttpUtil.doGet(access_token_url, param1);
        JSONObject jsonToken = JSONObject.fromObject(accessTokenObj);

        String openId = null;
        if (StringUtils.isNotBlank(String.valueOf(jsonToken))) {
            openId = jsonToken.getString("openid");
        }
        logger.info("获取openid，微信平台接口返回{}", openId);

        String urlToken = "https://api.weixin.qq.com/cgi-bin/token";
        TreeMap<String, String> param2 = new TreeMap<String, String>();
        param2.put("appid", Constants.APPID);
        param2.put("secret", Constants.APPSECRET);
        param2.put("grant_type", "client_credential");
        String tokenObj = HttpUtil.doGet(urlToken, param2);
        JSONObject retToken = JSONObject.fromObject(tokenObj);
        String accessToken = String.valueOf(retToken.get("access_token"));
        logger.info("获取access_token，微信平台接口返回{}", accessToken);

        TreeMap<String, TreeMap<String, String>> params = new TreeMap<String, TreeMap<String, String>>();
        //根据具体模板参数组装
        params.put("first", WechatTemplate.item("您的户外旅行活动订单已经支付完成，可在我的个人中心中查看", "#000000"));
        params.put("keyword1", WechatTemplate.item("发现尼泊尔—人文与自然的旅行圣地", "#000000"));
        params.put("keyword2", WechatTemplate.item("5000元", "#000000"));
        params.put("keyword3", WechatTemplate.item("2019.09.04", "#000000"));
        params.put("keyword4", WechatTemplate.item("5", "#000000"));
        params.put("remark", WechatTemplate.item("请届时携带好身份证件准时到达集合地点，若临时退改将产生相应损失，敬请谅解,谢谢！", "#000000"));
        WechatTemplate wechatTemplate = new WechatTemplate();
        wechatTemplate.setTemplate_id(Constants.TEMPLATEID);
        wechatTemplate.setTouser(openId);
        wechatTemplate.setUrl(url);
        wechatTemplate.setData(params);
        JSONObject json = JSONObject.fromObject(wechatTemplate);//将java对象转换为json对象
        String sendData = json.toString();//将json对象转换为字符串
        logger.info("板参数组装{}", sendData);

        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("access_token", accessToken);
        String retInfo = HttpUtil.doPost(SEND_TEMPLATE_MESSAGE_URL, treeMap, sendData);
        logger.info("消息模板返回{}", retInfo);
        return retInfo;
    }

}